<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>测试运输计划自动生成功能</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
      max-width: 1000px;
      margin: 0 auto;
      background-color: #f5f5f5;
    }

    .container {
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
    }

    h1,
    h2 {
      color: #333;
      border-bottom: 2px solid #409EFF;
      padding-bottom: 10px;
    }

    .form-group {
      margin-bottom: 15px;
    }

    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
      color: #555;
    }

    input,
    select {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 14px;
    }

    button {
      background: #409EFF;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-right: 10px;
    }

    button:hover {
      background: #337ecc;
    }

    button:disabled {
      background: #c0c4cc;
      cursor: not-allowed;
    }

    .result {
      margin-top: 20px;
      padding: 15px;
      border: 1px solid #e6e6e6;
      border-radius: 4px;
      background: #fafafa;
      white-space: pre-wrap;
      font-family: monospace;
      max-height: 400px;
      overflow-y: auto;
    }

    .error {
      color: #F56C6C;
      background: #FEF0F0;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    .success {
      color: #67C23A;
      background: #F0F9FF;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    .info {
      background: #e8f4fd;
      padding: 10px;
      border-radius: 4px;
      margin: 10px 0;
    }

    .test-step {
      background: #f8f9fa;
      padding: 15px;
      border-radius: 4px;
      margin: 10px 0;
      border-left: 4px solid #409EFF;
    }

    .feature-box {
      background: #e7f3ff;
      padding: 15px;
      border-radius: 4px;
      margin: 10px 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1>🚀 测试运输计划自动生成功能</h1>

    <div class="info">
      <strong>功能说明：</strong>
      <p>绑定定位器抽屉现在支持以下新功能：</p>
      <ul>
        <li>✅ 打开抽屉时自动检查运输计划数据</li>
        <li>✅ 如果没有运输计划，自动生成</li>
        <li>✅ 删除了手动"生成计划"按钮</li>
        <li>✅ 只保留"刷新"按钮（有数据时才显示）</li>
        <li>✅ 空状态提示改为"系统将自动生成"</li>
      </ul>
    </div>

    <div class="feature-box">
      <h3>🎯 改进前后对比</h3>
      <p><strong>改进前：</strong></p>
      <ul>
        <li>抽屉打开 → 显示空状态 → 用户手动点击"生成计划"按钮 → 生成运输计划</li>
      </ul>
      <p><strong>改进后：</strong></p>
      <ul>
        <li>抽屉打开 → 自动检查数据 → 如果没有数据则自动生成 → 显示运输计划</li>
      </ul>
    </div>
  </div>

  <div class="container">
    <h2>📋 测试步骤</h2>

    <div class="test-step">
      <h3>步骤1：准备测试数据</h3>
      <div class="form-group">
        <label for="billNo">运单编号:</label>
        <input type="text" id="billNo" placeholder="例如: YD202412250001" value="YD202412250001">
      </div>
      <button onclick="checkTransportPlan()" id="checkBtn">检查当前运输计划</button>
      <button onclick="clearTransportPlan()" id="clearBtn">清空运输计划数据</button>
    </div>

    <div class="test-step">
      <h3>步骤2：模拟绑定抽屉打开</h3>
      <p>模拟用户点击"绑定定位器"按钮时的逻辑：</p>
      <button onclick="simulateBindLocatorOpen()" id="simulateBtn" disabled>模拟绑定抽屉打开</button>
    </div>

    <div class="test-step">
      <h3>步骤3：验证自动生成</h3>
      <p>检查运输计划是否自动生成：</p>
      <button onclick="verifyAutoGeneration()" id="verifyBtn" disabled>验证自动生成结果</button>
    </div>
  </div>

  <div class="container">
    <h2>📊 测试结果</h2>
    <div id="result"></div>
  </div>

  <script>
    const baseURL = 'http://localhost:8080';
    let testData = {
      billNo: '',
      senderCity: '长春',
      receiverCity: '天津',
      hasInitialData: false
    };

    function showResult (title, data) {
      const resultDiv = document.getElementById('result');
      resultDiv.innerHTML = `
                <h3>${title}</h3>
                <div class="result">${JSON.stringify(data, null, 2)}</div>
            `;
    }

    function showError (message) {
      document.getElementById('result').innerHTML = `<div class="error">❌ 错误: ${message}</div>`;
    }

    function showSuccess (message) {
      document.getElementById('result').innerHTML = `<div class="success">✅ ${message}</div>`;
    }

    function appendResult (content) {
      const resultDiv = document.getElementById('result');
      resultDiv.innerHTML += content;
    }

    // 检查当前运输计划
    async function checkTransportPlan () {
      const billNo = document.getElementById('billNo').value;
      if (!billNo) {
        showError('请输入运单编号');
        return;
      }

      testData.billNo = billNo;

      try {
        showResult('检查运输计划', '正在查询...');

        const response = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
        const data = await response.json();

        console.log('运输计划查询结果:', data);

        if (data.code === 200) {
          testData.hasInitialData = data.rows && data.rows.length > 0;

          const resultHtml = `
                        <h3>📊 运输计划检查结果</h3>
                        <div class="info">
                            <p><strong>运单编号：</strong>${billNo}</p>
                            <p><strong>计划数量：</strong>${data.rows ? data.rows.length : 0} 条</p>
                            <p><strong>状态：</strong>${testData.hasInitialData ? '有数据' : '无数据'}</p>
                        </div>
                        ${testData.hasInitialData ?
              '<div class="success">✅ 当前有运输计划数据，测试自动生成需要先清空数据</div>' :
              '<div class="info">ℹ️ 当前无运输计划数据，适合测试自动生成功能</div>'
            }
                    `;

          document.getElementById('result').innerHTML = resultHtml;
          document.getElementById('simulateBtn').disabled = false;
        } else {
          showError('查询运输计划失败: ' + (data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('检查运输计划异常:', error);
        showError('检查运输计划异常: ' + error.message);
      }
    }

    // 清空运输计划数据
    async function clearTransportPlan () {
      const billNo = document.getElementById('billNo').value;
      if (!billNo) {
        showError('请输入运单编号');
        return;
      }

      try {
        showResult('清空运输计划', '正在清空...');

        // 先查询现有数据
        const listResponse = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
        const listData = await listResponse.json();

        if (listData.code === 200 && listData.rows && listData.rows.length > 0) {
          // 删除所有相关的运输计划
          const deletePromises = listData.rows.map(plan =>
            fetch(`${baseURL}/system/plan/${plan.id}`, { method: 'DELETE' })
          );

          await Promise.all(deletePromises);
          showSuccess(`成功清空 ${listData.rows.length} 条运输计划数据`);
          testData.hasInitialData = false;
        } else {
          showSuccess('运输计划数据已经为空');
        }

        document.getElementById('simulateBtn').disabled = false;
      } catch (error) {
        console.error('清空运输计划异常:', error);
        showError('清空运输计划异常: ' + error.message);
      }
    }

    // 模拟绑定抽屉打开
    async function simulateBindLocatorOpen () {
      const billNo = testData.billNo;

      try {
        showResult('模拟绑定抽屉打开', '正在模拟自动检查和生成过程...');

        let resultHtml = `
                    <h3>🔄 模拟绑定抽屉打开过程</h3>
                    <div class="info">
                        <p><strong>运单编号：</strong>${billNo}</p>
                        <p><strong>出发城市：</strong>${testData.senderCity}</p>
                        <p><strong>目的城市：</strong>${testData.receiverCity}</p>
                    </div>
                `;

        // 步骤1：检查现有数据
        resultHtml += `<p>🔍 步骤1：检查现有运输计划数据...</p>`;

        const checkResponse = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
        const checkData = await checkResponse.json();

        if (checkData.code === 200) {
          const planCount = checkData.rows ? checkData.rows.length : 0;
          resultHtml += `<p>📊 查询结果：找到 ${planCount} 条运输计划记录</p>`;

          if (planCount === 0) {
            // 步骤2：自动生成
            resultHtml += `<p>🚀 步骤2：未找到数据，开始自动生成...</p>`;

            const analysisResponse = await fetch(`${baseURL}/pack/locationLog/analysis/cityTransit?departureCity=${encodeURIComponent(testData.senderCity)}&destinationCity=${encodeURIComponent(testData.receiverCity)}`);
            const analysisData = await analysisResponse.json();

            if (analysisData.code === 200 && analysisData.data && analysisData.data.passedCities) {
              resultHtml += `<p>✅ 分析接口调用成功，获得 ${analysisData.data.passedCities.length} 个城市</p>`;

              // 模拟保存过程
              resultHtml += `<p>💾 步骤3：保存运输计划到数据库...</p>`;

              resultHtml += `<p>✅ 自动生成完成！</p>`;
            } else {
              resultHtml += `<p>❌ 分析接口调用失败或无数据</p>`;
            }
          } else {
            resultHtml += `<p>ℹ️ 已有运输计划数据，跳过自动生成</p>`;
          }
        }

        document.getElementById('result').innerHTML = resultHtml;
        document.getElementById('verifyBtn').disabled = false;

      } catch (error) {
        console.error('模拟过程异常:', error);
        showError('模拟过程异常: ' + error.message);
      }
    }

    // 验证自动生成结果
    async function verifyAutoGeneration () {
      const billNo = testData.billNo;

      try {
        showResult('验证自动生成结果', '正在验证...');

        const response = await fetch(`${baseURL}/system/plan/list?billNo=${encodeURIComponent(billNo)}`);
        const data = await response.json();

        if (data.code === 200) {
          const planCount = data.rows ? data.rows.length : 0;

          let resultHtml = `
                        <h3>🎯 自动生成验证结果</h3>
                        <div class="info">
                            <p><strong>运单编号：</strong>${billNo}</p>
                            <p><strong>生成计划数量：</strong>${planCount} 条</p>
                        </div>
                    `;

          if (planCount > 0) {
            resultHtml += `<div class="success">✅ 自动生成功能正常！成功生成了 ${planCount} 条运输计划</div>`;

            resultHtml += `
                            <h4>生成的运输计划详情：</h4>
                            <table style="width:100%; border-collapse: collapse; margin-top: 10px;">
                                <thead>
                                    <tr style="background: #f8f9fa;">
                                        <th style="border: 1px solid #ddd; padding: 8px;">顺序</th>
                                        <th style="border: 1px solid #ddd; padding: 8px;">城市</th>
                                        <th style="border: 1px solid #ddd; padding: 8px;">节点类型</th>
                                        <th style="border: 1px solid #ddd; padding: 8px;">累计耗时(小时)</th>
                                    </tr>
                                </thead>
                                <tbody>
                        `;

            data.rows.forEach(plan => {
              resultHtml += `
                                <tr>
                                    <td style="border: 1px solid #ddd; padding: 8px; text-align: center;">${plan.passOrder || '-'}</td>
                                    <td style="border: 1px solid #ddd; padding: 8px;">${plan.city || '-'}</td>
                                    <td style="border: 1px solid #ddd; padding: 8px; text-align: center;">${plan.nodeType || '-'}</td>
                                    <td style="border: 1px solid #ddd; padding: 8px; text-align: center;">${plan.estimatedDuration || '-'}</td>
                                </tr>
                            `;
            });

            resultHtml += `
                                </tbody>
                            </table>
                        `;

            resultHtml += `
                            <div class="feature-box" style="margin-top: 15px;">
                                <h4>✨ 功能优势</h4>
                                <ul>
                                    <li>用户体验优化：无需手动操作，系统自动处理</li>
                                    <li>界面简化：移除了手动生成按钮，界面更简洁</li>
                                    <li>逻辑合理：打开抽屉即可看到完整的运输计划</li>
                                    <li>效率提升：减少用户操作步骤，提高工作效率</li>
                                </ul>
                            </div>
                        `;
          } else {
            resultHtml += `<div class="error">❌ 自动生成可能存在问题，未找到生成的运输计划</div>`;
          }

          document.getElementById('result').innerHTML = resultHtml;
        } else {
          showError('验证失败: ' + (data.msg || '未知错误'));
        }
      } catch (error) {
        console.error('验证异常:', error);
        showError('验证异常: ' + error.message);
      }
    }

    // 页面加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function () {
      console.log('运输计划自动生成功能测试页面已加载');
    });
  </script>
</body>

</html>